<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'material:receive:pmMaterialneedArr:edit'"
    @register="registerDrawer"
    @ok="handleSubmit('0')"
    width="60%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #clSelect>
        <ListSelect
          selectType="materialSelect"
          :checkbox="true"
          :params="queryParams"
          :selectList="listSelectRef"
          @select="handSelect"
        />
      </template>
      <template #pmMaterialneedArrsList>
        <BasicTable
          @register="registerPmMaterialneedArrsTable"
          @row-click="handlePmMaterialneedArrsRowClick"
        />
        <a-button
          v-if="record.status != '0'"
          class="mt-2"
          @click="handlePmMaterialneedArrsAdd"
          v-auth="'material:receive:pmMaterialneedArr:edit'"
        >
          <Icon icon="ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button>
      </template>
    </BasicForm>
    <template #centerFooter>
      <a-button
        v-if="record.status != '0'"
        class="mt-2"
        type="success"
        @click="handleSubmit('1')"
        v-auth="'material:receive:pmMaterialneedArr:edit'"
      >
        <Icon icon="ant-design:check-outlined" /> {{ t('保存并提交') }}
      </a-button>
    </template>
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsMaterialReceivePmMaterialneedArrForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import {
    PmMaterialneedArr,
    pmMaterialneedArrSave,
    pmMaterialneedArrForm,
  } from '/@/api/material/receive/pmMaterialneedArr';
  import { ListSelect } from '/@/components/ListSelect';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('material.receive.pmMaterialneedArr');
  const { showMessage } = useMessage();
  const record = ref<PmMaterialneedArr>({} as PmMaterialneedArr);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增材料收货') : t('编辑材料收货'),
  }));

  let queryParams = ref({});
  let listSelectRef = ref([]);

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('工程编号'),
      field: 'projectno',
      component: 'Input',
      dynamicDisabled: true,
      componentProps: {
        maxlength: 100,
      },
      required: true,
    },
    {
      label: t('工程名称'),
      field: 'name',
      component: 'Input',
      dynamicDisabled: true,
      componentProps: {
        maxlength: 200,
      },
    },
    {
      label: t('收货日期'),
      field: 'arrDate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        // showTime: { format: 'HH:mm' },
      },
      // required: true,
    },
    {
      label: t('材料清单'),
      field: 'clid1',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'clSelect',
      show: false,
    },
    {
      label: t('单据号'),
      field: 'djno',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      show: false,
    },
    {
      label: t('分单编号'),
      field: 'fdno',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      show: false,
    },
    {
      label: t('设计变更单号'),
      field: 'sno',
      component: 'Input',
      componentProps: {
        maxlength: 200,
      },
      show: false,
    },

    {
      label: t('计划ID'),
      field: 'needId',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      show: false,
    },
    {
      label: t('备注信息'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('现场图片'),
      field: 'dataMap',
      component: 'Upload',
      componentProps: {
        loadTime: computed(() => record.value.__t),
        bizKey: computed(() => record.value.id),
        bizType: 'PmMaterialneedArr_image',
        uploadType: 'image',
        isPreview: true,
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('到货单'),
      field: 'dataMap',
      component: 'Upload',
      componentProps: {
        loadTime: computed(() => record.value.__t),
        bizKey: computed(() => record.value.id),
        bizType: 'PmMaterialneedArrAsn_image',
        uploadType: 'image',
        isPreview: true,
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('材料收货子表'),
      field: 'pmMaterialneedArrsList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'pmMaterialneedArrsList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 24, md: 24 },
  });

  const [registerPmMaterialneedArrsTable, pmMaterialneedArrsTable] = useTable({
    actionColumn: {
      width: 60,
      actions: (record1: Recordable) => [
        {
          icon: 'ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handlePmMaterialneedArrsDelete.bind(this, record1),
          },
          auth: 'material:receive:pmMaterialneedArr:edit',
          ifShow: () => record.value.status != '0',
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setPmMaterialneedArrsTableData(_res: Recordable) {
    pmMaterialneedArrsTable.setColumns([
      {
        title: t('物料/水表编号'),
        dataIndex: 'basInv.mcode',
        width: 130,
        align: 'left',
      },
      {
        title: t('物料/水表名称'),
        dataIndex: 'basInv.mname',
        width: 100,
        align: 'left',
      },
      {
        title: t('规格型号'),
        dataIndex: 'basInv.mstd',
        width: 130,
        align: 'left',
      },
      {
        title: t('供应商'),
        dataIndex: 'supplier',
        width: 130,
        align: 'left',
      },
      {
        title: t('需求数量'),
        dataIndex: 'querycount',
        width: 80,
        align: 'left',
      },
      {
        title: t('收货数量'),
        dataIndex: 'actualnum',
        width: 130,
        align: 'left',
        editRow: true,
        edit: true,
        // editable: true,
        editComponent: 'InputNumber',
        editComponentProps: {
          maxlength: 16,
        },
        editRule: true,
      },
      // {
      //   title: t('来源ID'),
      //   dataIndex: 'sourceId',
      //   width: 130,
      //   align: 'left',
      //   editRow: true,
      //   editComponent: 'Input',
      //   editComponentProps: {
      //     maxlength: 64,
      //   },
      //   editRule: true,
      // },
    ]);
    pmMaterialneedArrsTable.setTableData(record.value.pmMaterialneedArrsList || []);
  }

  function handlePmMaterialneedArrsRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handlePmMaterialneedArrsAdd() {
    listSelectRef.value = [];
    document.getElementById('form_item_clid1')?.click();
    // pmMaterialneedArrsTable.insertTableDataRecord({
    //   id: new Date().getTime(),
    //   isNewRecord: true,
    //   editable: true,
    // });
  }

  function handlePmMaterialneedArrsDelete(record: Recordable) {
    pmMaterialneedArrsTable.deleteTableDataRecord(record);
  }

  async function getPmMaterialneedArrsList() {
    let pmMaterialneedArrsListValid = true;
    let pmMaterialneedArrsList: Recordable[] = [];
    for (const record of pmMaterialneedArrsTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        pmMaterialneedArrsListValid = false;
      }
      pmMaterialneedArrsList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of pmMaterialneedArrsTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      pmMaterialneedArrsList.push({
        ...record,
        status: '1',
      });
    }
    if (!pmMaterialneedArrsListValid) {
      throw { errorFields: [{ name: ['pmMaterialneedArrsList'] }] };
    }
    return pmMaterialneedArrsList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await pmMaterialneedArrForm({ id: data.id });
    record.value = (res.pmMaterialneedArr || {}) as PmMaterialneedArr;
    if (!data.id) {
      record.value = { ...record.value, ...data };
    }
    record.value.__t = new Date().getTime();

    setDrawerProps({ showOkBtn: record.value.status == '0' ? false : true });
    queryParams.value = {
      pcode: record.value.projectno,
    };
    setFieldsValue(record.value);
    setPmMaterialneedArrsTableData(res);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit(ope) {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      if (ope === '1') {
        // 保存并提交
        data.status = '0';
      }
      data.pmMaterialneedArrsList = await getPmMaterialneedArrsList();
      // console.log('submit', params, data, record);
      const res = await pmMaterialneedArrSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }

  async function handSelect(selectData) {
    let arr = await pmMaterialneedArrsTable.getDataSource();
    selectData.forEach((item) => {
      let flag = true;
      arr.forEach((res) => {
        if (res.metercode == item.mcode) {
          flag = false;
        }
      });
      if (flag) {
        pmMaterialneedArrsTable.insertTableDataRecord({
          ...item,
          // id: new Date().getTime() + item.id,
          editable: true,
          isNewRecord: true,
          basInv: {
            mcode: item.mcode,
            mname: item.mname,
            mstd: item.mstd,
          },
          metercode: item.mcode,
          querycount: item.num,
          actualnum: item.num,
          sourceId: item.id,
          projectno: item.pcode,
        });
      }
    });
  }
</script>
<style lang="less" scoped>
  :deep(.jeesite-editable-cell__action) {
    display: none;
  }

  /* .jeesite-editable-cell__action {
    display: none;
  } */

  :deep(.edit-cell-align-center) {
    width: 100% !important;
  }
</style>
